import store from "@/store"

/*
 * cs 2020-4-30
 * 处理 时间格式为"01:20"字符串转数字
 */
function timeToNum(time) {
	if (!time) {
		return 0;
	}
	try {
		let tampArr = time.split(':');
		if (tampArr.length === 2) {
			let tampNum = Number(tampArr[0]) * 60 + Number(tampArr[1]);
			return tampNum;
		} else {
			return 0;
		}
	} catch (err) {
		return 0;
	}
}
/*
 * cs 2019-12-26
 * 格式化时间
 */
function dateFormat(date, format) {
	if (!date || !format) {
		return '';
	}
	if (typeof date != "number") {
		date = date + '';
		if (date.indexOf("T") < 0) {
			date = date.replace(/-/g, '/')
		}
	}
	date = new Date(new Date(date).getTime());
	let map = {
		M: date.getMonth() + 1,
		d: date.getDate(),
		h: parseInt(date.getHours()),
		m: date.getMinutes(),
		s: date.getSeconds(),
		q: Math.floor((date.getMonth() + 3) / 3),
		S: date.getMilliseconds() //毫秒
	};
	format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
		let v = map[t];
		if (v !== undefined) {
			if (all.length > 1) {
				v = '0' + v;
				v = v.substr(v.length - 2);
			}
			return v;
		} else if (t === 'y') {
			return (date.getFullYear() + '').substr(4 - all.length);
		}
		return all;
	});
	return format;
}
/*
 * cs 2020-4-30
 * 处理 数字转为时间格式为"01:20"
 */
function NumToString(num) {
	if (!num) {
		return '00:00';
	}
	try {
		if (num >= 60 * 60) {
			let h = Math.floor((num / 60) * 60).toString();
			let m = Math.floor(num / 60).toString();
			let s = Math.round(num % 60).toString();
			h = h.length > 1 ? h : '0' + h;
			m = m.length > 1 ? m : '0' + m;
			s = s.length > 1 ? s : '0' + s;
			return m + ':' + s;
		} else {
			let m = Math.floor(num / 60).toString();
			let s = Math.round(num % 60).toString();
			m = m.length > 1 ? m : '0' + m;
			s = s.length > 1 ? s : '0' + s;
			return m + ':' + s;
		}
	} catch (err) {
		return '00:00';
	}
}

/**
 * 计算百分百四舍五入
 * @param {*} num
 * @param {*} total
 */
function Percentage(num, total) {
	return Math.round((num / total) * 10000) / 100.0 + '%'; // 小数点后两位百分比
}

/*
 * cs 2020-5-2
 * 获取浏览器
 */
function getBrow() {
	let u = navigator.userAgent;
	let ua = navigator.userAgent.toLocaleLowerCase();
	let app = navigator.appVersion;
	return {
		trident: u.indexOf('Trident') > -1,
		/*IE内核*/
		presto: u.indexOf('Presto') > -1,
		/*opera内核*/
		webKit: u.indexOf('AppleWebKit') > -1,
		/*苹果、谷歌内核*/
		gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
		/*火狐内核*/
		mobile: !!u.match(/AppleWebKit.*Mobile.*/),
		/*是否为移动终端*/
		ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
		/*ios终端*/
		android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
		/*android终端或者uc浏览器*/
		iPhone: u.indexOf('iPhone') > -1,
		/*是否为iPhone或者QQHD浏览器*/
		iPad: u.indexOf('iPad') > -1,
		/*是否iPad*/
		webApp: u.indexOf('Safari') == -1,
		/*是否web应该程序，没有头部与底部*/
		souyue: u.indexOf('souyue') > -1,
		superapp: u.indexOf('superapp') > -1,
		weixin: u.toLowerCase().indexOf('micromessenger') > -1,
		qq: ua.match(/QQ/i) == "qq", // QQ
		weiBo: ua.match(/WeiBo/i) == "weibo", // 微博
		Safari: u.indexOf('Safari') > -1,
		QQbrw: u.indexOf('MQQBrowser') > -1, // QQ浏览器
		webview: !(u.match(/Chrome\/([\d.]+)/) || u.match(/CriOS\/([\d.]+)/)) && u.match(
			/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
		ucweb: function() {
			try {
				return parseFloat(u.match(/ucweb\d+\.\d+/gi).toString().match(/\d+\.\d+/).toString()) >= 8.2
			} catch (e) {
				if (u.indexOf('UC') > -1) {
					return true;
				}
				return false;
			}
		}(),

		Symbian: u.indexOf('Symbian') > -1,
		ucSB: u.indexOf('Firofox/1.') > -1,
	};
}

/*
 * cs 2020-5-20
 * 获取平台
 * @return code  1:网页 2:安卓APP 3：iosAPP 4:H5
 */
function getSystemType() {
	// #ifdef H5
	return 4;
	// #endif
	// #ifdef APP-PLUS
	let code = 2;
	switch (uni.getSystemInfoSync().platform) {
		case 'android':
			code = 2;
			break;
		case 'ios':
			code = 3;
			break;
	}
	return code;
	// #endif
}
/*
 * cs 2020-5-20
 * 字符串转为数组
 */
function strToAar(str, k) {
	let k = k || ',';
	if (!str) {
		return [];
	}
	return str.split(k);
}

/*
 * cs 2020-6-27
 * 时间转换为时间戳
 */
function dateStrtoNum(tiem) {
	tiem = tiem + '';
	tiem = tiem.replace(/-/g, '/');
	return (new Date(tiem)).getTime()
}

/* 
 * 获取url字符串参数
 */
function getRequestParameters(locationhref) {
	let href = locationhref || "";
	let theRequest = new Object();
	let str = href.split("?")[1];
	if (str != undefined) {
		let strs = str.split("&");
		for (let i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
		}
	}
	return theRequest;
}


/* 
 * obj 转 params字符串参数  
 * 例子：{a:1,b:2} => a=1&b=2
 */
function objParseParam(obj) {
	let paramsStr = "";
	if (obj instanceof Array) return paramsStr;
	if (!(obj instanceof Object)) return paramsStr;
	for (let key in obj) {
		paramsStr += `${key}=${obj[key]}&`;
	}
	return paramsStr.substring(0, paramsStr.length - 1);
}

/*
 * cs 2020-8-1
 * 过滤 特殊字符表情 过滤脚本
 */
function specialStrFilter(value) {
	let specialStrFilterReg =
		/[^A-Za-z0-9_\-\u4e00-\u9fa5\~\`\!\@\#\$\%\^\&\*\(\)\-\+\=\[\{\]\}\;\:\,\.\?\<\>\/\·\~\！\￥\……\&\*\（\）\——\「\【\】\」\|\、\|\；\’\：\“\《\》\？\，\。\、\\\'\"]+/g;
	value = value.replace(specialStrFilterReg, '');
	value = value.replace(/&/g, '&amp;');
	value = value.replace(/</g, '&lt;');
	value = value.replace(/>/g, '&gt;');
	value = value.replace(/"/g, '&quto;');
	value = value.replace(/'/g, '&#39;');
	value = value.replace(/`/g, '&#96;');
	value = value.replace(/\//g, '&#x2F;');
	value = value.replace(/(\r\n|\r|\n)+/g, '');
	return value
}

/**
 * @author chenshuai 2020-5-19
 * @function 获取字典的字段
 * @param {string} num 比较的值
 * @param {array} obj  取值数组
 * @param {string} key 取值属性
 * @param {string} code='code' 比较值的属性
 */
function getObjKey(num, obj, key, code = 'code') {
	let tampObj = obj.find(item => {
		return item[code] == num
	})
	if (tampObj) {
		return tampObj[key] || "未知"
	} else {
		return "未知"
	}
}


//防抖函数
function debounce(fn, wait = 500, isImmediate = false) {
	let timerId = null;
	let flag = true;
	if (isImmediate) {
		return function() {
			clearTimeout(timerId);
			if (flag) {
				console.log("只执行第一次");
				fn.apply(this, arguments);
				flag = false
			}
			timerId = setTimeout(() => {
				flag = true
			}, wait)
		}
	}
	return function() {
		clearTimeout(timerId);
		timerId = setTimeout(() => {
			fn.apply(this, arguments)
		}, wait)
	}
}

/*
 * cs 2020-9-17
 * 将省 市 县转为索引 和 中文
 */
function getAreaText(codeList, allareas) {
	if (typeof codeList != 'object') {
		return {};
	}
	let regions = [];
	let regionsIndex = [];
	let provinceCode = codeList[0];
	let provinceIndex = allareas.findIndex(item => {
		return item.id == provinceCode;
	});
	if (provinceIndex >= 0) {
		regionsIndex.push(provinceIndex);
		regions.push(allareas[provinceIndex].label);
	} else {
		return {
			indexList: regionsIndex,
			nameList: regions
		};
	}

	let cityList = allareas[provinceIndex].children;

	let cityCode = codeList[1];

	let cityIndex = cityList.findIndex(item => {
		return item.id == cityCode;
	});

	if (cityIndex >= 0) {
		regionsIndex.push(cityIndex);
		regions.push(cityList[cityIndex].label);
	} else {
		return {
			indexList: regionsIndex,
			nameList: regions
		};
	}


	let areaList = cityList[cityIndex].children;

	let areaCode = codeList[2];

	let areaIndex = areaList.findIndex(item => {
		return item.id == areaCode;
	});

	if (areaIndex >= 0) {
		regionsIndex.push(areaIndex);
		regions.push(areaList[areaIndex].label);
	} else {
		return {
			indexList: regionsIndex,
			nameList: regions
		};
	}

	return {
		indexList: regionsIndex,
		nameList: regions
	};
}


function getTodayDate() {
	let date = new Date();
	let y = date.getFullYear();
	let m = date.getMonth() + 1;
	m = m > 9 ? m : '0' + m;
	let d = date.getDate();
	d = d > 9 ? d : '0' + d;
	return y + "-" + m + "-" + d
}

/*
 * cs 2020-9-30
 * 打乱数组排序
 */
function disorganizeArr(arr) {
	return arr.sort(function() {
		return 0.5 - Math.random();
	})
}

/*
 * cs 2020-10-16
 * 将数据转化为日历规则 string
 * usc_type FIXED代表每周 DAY 代表间隔时间
 * usc_days 当usc_type为FIXED 为 1,2,3 1代表周一
 * 当usc_type为DAY 为 7代表间隔时间
 */
function getCalendarRrule(usc_type, usc_days, end_date) {
	if (usc_type && usc_days) {
		let rrule = {
			FREQ: "",
			INTERVAL: "",
			WKST: "SU",
			BYDAY: [],
			UNTIL: ""
		};
		if (end_date) {
			rrule.UNTIL = dateFormat(end_date, "yyyy|MM|dd|T|hh|mm|ss|Z").replace(/\|/g, "");
		}

		if (usc_type == "FIXED") {
			rrule.FREQ = "WEEKLY";
			let weekRruleList = store.state.dictionaries.weekRruleList;
			usc_days = usc_days.split(",");
			usc_days.forEach(item => {
				rrule.BYDAY.push(weekRruleList[item - 1]);
			})
			rrule.BYDAY = rrule.BYDAY.join(",");
		} else {
			rrule.BYDAY = rrule.BYDAY.join(",");
			rrule.FREQ = "DAILY";
			rrule.INTERVAL = usc_days;
		}
		let tampStr = "";
		for (let k in rrule) {
			if (rrule[k] && rrule[k]) {
				tampStr += k + "=" + rrule[k] + ";"
			}
		}
		return tampStr;
		console.log(tampStr);
	} else {
		return ""
	}
}

/*
 * cs 2020-10-16
 * 获取提醒 提前 分钟
 */
function getReminderList(arr) {
	// 先求最大值
	let maxTime = [];
	arr.forEach(item => {
		if (maxTime.length == 0) {
			maxTime = [item[0], item[1]];
		} else {
			if (Number(item[0]) * 60 + Number(item[1]) > Number(maxTime[0]) * 60 + Number(maxTime[1])) {
				maxTime = [item[0], item[1]];
			}
		}
	})


	let tampArr = [];
	arr.forEach(item => {
		tampArr.push((Number(maxTime[0]) - item[0]) * 60 + Number(maxTime[1]) - (item[1]));
	})
	return {
		maxTime: maxTime,
		reminderList: tampArr
	};
}

/*
 * cs 2020-11-26
 * 去掉富文本标签
 */
function removeDomLable(str) {
	return str.replace(/<[^>]+>/gi, "");
}


/*
 * cs 2021-6-1
 */
function dataURLtoFile(dataurl, filename) {
	let arr = dataurl.split(',');
	let mime = arr[0].match(/:(.*?);/)[1];
	let bstr = atob(arr[1]);
	let n = bstr.length;
	let u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	//转换成file对象
	return new File([u8arr], filename, {
		type: mime
	});
}

/*
 * cs 2021-6-1
 * 安卓获取相机权限
 * android.permission.CAMERA
 */
function getCameraJurisdiction(sucFun, errFun) {
	if (uni.getSystemInfoSync().platform == "android") {
		plus.android.requestPermissions(['android.permission.CAMERA'],
			function(e) {
				if (e.deniedAlways.length > 0) { //权限被永久拒绝
					// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
					console.log('Always Denied!!! ' + e.deniedAlways.toString());
					if (errFun && typeof errFun == "function") {
						errFun({
							msg: "权限被永久拒绝了"
						})
					}
				}
				if (e.deniedPresent.length > 0) { //权限被临时拒绝
					if (errFun && typeof errFun == "function") {
						errFun({
							msg: "权限被临时拒绝了"
						})
					}
					// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
					console.log('Present Denied!!! ' + e.deniedPresent.toString());
				}
				if (e.granted.length > 0) { //权限被允许
					//调用依赖获取定位权限的代码
					console.log("获取权限成功");
					if (sucFun && typeof sucFun == 'function') {
						sucFun();
					}
				}
			})
	}
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
function checkRole(value) {
	if (value && value instanceof Array && value.length > 0) {
		const roles = store.getters && store.getters.roles
		const permissionRoles = value

		const hasRole = roles.some(role => {
			return permissionRoles.includes(role)
		})

		if (!hasRole) {
			return false
		}
		return true
	} else {
		console.error(`need roles! Like checkRole="['admin','editor']"`)
		return false
	}
}



export {
	getUserByToken,
	timeToNum,
	Percentage,
	dateFormat,
	NumToString,
	getBrow,
	getSystemType,
	strToAar,
	dateStrtoNum,
	getRequestParameters,
	specialStrFilter,
	objParseParam,
	getObjKey,
	debounce,
	getAreaText,
	getTodayDate,
	disorganizeArr,
	getCalendarRrule,
	getReminderList,
	removeDomLable,
	dataURLtoFile,
	getCameraJurisdiction,
	checkRole
};
